#!/usr/bin/env python

# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START imports]
import os
import urllib
import time
import json

from google.appengine.api import users
from google.appengine.ext import ndb

import jinja2
import webapp2

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)
# [END imports]

DEFAULT_GUESTBOOK_NAME = 'default_user_test'


# We set a parent key on the 'Greetings' to ensure that they are all
# in the same entity group. Queries across the single entity group
# will be consistent. However, the write rate should be limited to
# ~1/second.

class user(ndb.Model):
    """A main model for representing an individual Guestbook entry."""
    id = ndb.KeyProperty(indexed=True)
    name = ndb.StringProperty(indexed=True)
    password = ndb.IntegerProperty(indexed=True)


class place(ndb.Model):
    """A main model for representing an individual Guestbook entry."""
    id = ndb.KeyProperty(indexed=True)
    userid = ndb.StringProperty(indexed=True)
    searchTime = ndb.FloatProperty(indexed=True)
    searchText = ndb.StringProperty(indexed=True)


# [START main_page]
class MainPage(webapp2.RequestHandler):

    def get(self):

        user = users.get_current_user()
        if user:
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
            isgoogle = 1
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Google Login'
            isgoogle = 0

        template_values = {
            'user': user,
            'isgoogle': isgoogle,
            'url': url,
            'url_linktext': url_linktext,
        }
        template = JINJA_ENVIRONMENT.get_template('index.html')
        self.response.write(template.render(template_values))


# [END main_page]

class Login(webapp2.RequestHandler):

    def post(self):
        # We set the same parent key on the 'Greeting' to ensure each
        # Greeting is in the same entity group. Queries across the
        # single entity group will be consistent. However, the write
        # rate to a single entity group should be limited to
        # ~1/second.

        p_id = self.request.get('id')
        password = int(self.request.get('password'))

        query = user.query(user.id == ndb.Key("user", p_id), user.password == password).fetch()
        template_values = {}
        if len(query) == 0:
            template_values['msg'] = 'User id or password is invalid'
        else:
            template_values['user'] = query[0]
            template_values['id'] = p_id

        html = 'index.html'
        template = JINJA_ENVIRONMENT.get_template(html)
        self.response.write(template.render(template_values))


class getPlace(webapp2.RequestHandler):

    def get(self):
        p_id = self.request.get('id')
        queryPlace = place.query(place.userid == p_id).fetch()
        p_place = [];
        if len(queryPlace) > 0:
            for qp in queryPlace:
                placeData = {'searchText': qp.searchText}
                p_place.append(placeData)

        self.response.write(json.dumps(p_place))


class loginOut(webapp2.RequestHandler):

    def get(self):
        user = users.get_current_user()
        if user:
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
            isgoogle = 1
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Google Login'
            isgoogle = 0

        template_values = {
            'user': user,
            'isgoogle': isgoogle,
            'url': url,
            'url_linktext': url_linktext,
        }

        template = JINJA_ENVIRONMENT.get_template('index.html')
        self.response.write(template.render(template_values))


class addSearch(webapp2.RequestHandler):

    def get(self):
        # We set the same parent key on the 'Greeting' to ensure each
        # Greeting is in the same entity group. Queries across the
        # single entity group will be consistent. However, the write
        # rate to a single entity group should be limited to
        # ~1/second.
        userid = self.request.get('userid')
        searchText = self.request.get('searchText')
        queryPlace = place.query(place.searchText == searchText, place.userid == userid).fetch()
        au = place()
        if len(queryPlace) != 0:
            au = queryPlace[0]
        au.userid = userid
        au.searchTime = time.time()
        au.searchText = searchText
        au.put()

        user = users.get_current_user()
        if user:
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
            isgoogle = 1
            template_values = {
                'user': user,
                'isgoogle': isgoogle,
                'url': url,
                'url_linktext': url_linktext,
            }
        else:
            isgoogle = 0
            query = user.query(user.id == ndb.Key("user", userid)).fetch()
            template_values = {'user': query[0], 'id': userid}

        template = JINJA_ENVIRONMENT.get_template('index.html')
        self.response.write({'code': 0, 'msg': 'success'})


# [START app]
app = webapp2.WSGIApplication([
    ('/', MainPage),
    # ('/addUser', AddUser),
    # ('/toName', ToName),
    # ('/toPassword', ToPassword),
    ('/login', Login),
    ('/loginOut', loginOut),
    ('/addSearch', addSearch),
    ('/getPlace', getPlace),
    # ('/password', Password),
    # ('/delete', DeleteGuestbook),
], debug=True)
# [END app]
